package dkbta.util;

import dkbta.ontology.elements.Element;

/**
 * A compound object containing an element instance, an index, one of the element's time
 * interval's ends and whether that time is the start or end time.<br>
 * This object is used when chronologically ordering the time ends of elements for
 * detecting overlaps of multiple elements.
 * 
 * @author Uri Kanonov
 */
public class InstanceTime implements Comparable<InstanceTime>{
	public final Element element;

	public final int elementIndex;

	public final boolean isStart;

	private final long _time;

	public InstanceTime(Element element, int elementIndex, long time, boolean isStart){
		this.element = element;
		this.elementIndex = elementIndex;
		this.isStart = isStart;
		_time = time;
	}

	/**
	 * Comparing two instance-time pairs first by time, earlier time is "smaller". If the
	 * times are equal, instances that are "start" are "smaller". If both instances are
	 * "start" then those with a null element field are considered "smaller". If both
	 * instances are "end" then those with a non-null element field are considered
	 * "smaller"
	 */
	@Override
	public int compareTo(InstanceTime other){
		// Earlier time is "smaller"
		long cmp = _time - other._time;
		if (cmp < 0){
			return -1;
		}else if (cmp > 0){
			return 1;
		}else{
			// If the times are equal, instances that are "start" are "smaller"
			if (isStart){
				if (other.isStart){
					// If both instances are "start" then those with a
					// null element field are considered "smaller"
					if (element == null){
						return -1;
					}else{
						return 1;
					}
				}else{
					return -1;
				}
			}else{
				if (other.isStart){
					return 1;
				}else{
					// If both instances are "end" then those with a
					// non-null element field are considered "smaller"
					if (element == null){
						return 1;
					}else{
						return -1;
					}
				}
			}
		}
	}

	@Override
	public String toString(){
		return (element == null ? "<no-e>" : element.getName()) + "-"
				+ ((isStart) ? "S" : "E") + _time;
		// + TimeUtils.timeOnly(_time);
	}
}
